package com.product;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dao.ProductDao;
import com.vo.Category;
import com.vo.Product;

public class Product_Modify extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int flag = 0; //
		String ep_name = null;//商品名称
		int ep_id = 0; //商品id
		int epc_id = 0;//商品分类一级id
		int epc_cid = 0;//二级ID
		int ep_stock = 0;//商品库存
		float ep_price =0;//商品价格
		//session拿到前一个servlet传递的分类值
		HttpSession session = request.getSession();
		ProductDao dao = new ProductDao();
		List<Category> list = new ArrayList<Category>();
		Category category = null;
		Product product = new Product();
		//判断id不为空接收ID值用于修改
		
			//此处try的原因：转换成int是有可能会出现异常
			try {
				ep_id = Integer.parseInt(request.getParameter("iid"));
				System.out.println(ep_id);
			} catch (Exception e) {
		
			}
		
		//得到jsp页面的商品名字
		ep_name = request.getParameter("productName");
		//此处try的原因：转换成int是有可能会出现异常
		try {
			//...
			ep_stock = Integer.parseInt(request.getParameter("productStock"));
			//...
			ep_price = Float.parseFloat(request.getParameter("productPrice"));
			//...
			epc_id = Integer.parseInt(request.getParameter("parentId"));
		} catch (Exception e) {
			
		}
		//得到分类值
		list = (List)session.getAttribute("productClassify");
		//遍历通过前台jsp页面选中分类传来的ID值在分类值中找出对应的值
		for(int a=0;a<list.size();a++){
			
			if(epc_id == list.get(a).getEpc_id()){
				category = list.get(a);
				break;
			}
		}
		//找到值 赋值
		epc_id = category.getEpc_id();
		epc_cid = category.getEpc_parent_id();
		
		product.setEp_id(ep_id);
		product.setEp_name(ep_name);
		product.setEp_price(ep_price);
		product.setEp_stock(ep_stock);
		product.setEpc_id(epc_id);
		product.setEpc_child_id(epc_cid);
		//调用修改方法：
		try {
			flag = dao.update(product);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(flag > 0){
			response.sendRedirect("product_view");
		}else{
			response.sendRedirect("manage/err.jsp");
		}
		
	}
	

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
